package com.jxjiang.chatapplication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.jxjiang.chatapplication.client.ChatClientAndroid;

import top.xx252016.coreClient.base.Contract;


public class ChatService extends Service {

    private final IBinder mBinder = new LocalBinder();
    Contract.AppContract mContract;
    Contract.SubThreadContract mSubThreadContract;
    Thread mThread;
    public ChatService() {
    }

    @Override
    public void onCreate() {
        Log.d("jw", "onCreate:service ");
        mThread =new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("jw", "run: sssssssss");
                Looper.prepare();
                mSubThreadContract = new ChatClientAndroid(mContract);
                threadHandler = new Handler(Looper.myLooper());
                Log.d("jw", "run: start socket before");
                mSubThreadContract.start();
                Log.d("jw", "run: loop before");
                Looper.loop();
                Log.d("jw", "run: loop after ");
            }
        });
        mThread.start();
        super.onCreate();
    }

    public void setContract(Contract.AppContract contract){
        mContract = contract;
        if(mSubThreadContract !=null){
            ((ChatClientAndroid)mSubThreadContract).setSubContract(mContract);
        }
    }

    Handler threadHandler;

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.e("jw", "onStart: ");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("jw", "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e("jw", "onBind: " );
        return mBinder;
    }
    private void submit(final String string){
        mSubThreadContract.fecth2Socket(string);
    }

    public void submit2Handler(final String content){
        threadHandler.post(new Runnable() {
            @Override
            public void run() {
                submit(content);
            }
        });
    }

    @Override
    public void onDestroy() {
        Log.d("jw", "onDestroy: service");
        mSubThreadContract.quit();
        threadHandler.getLooper().quit();
        super.onDestroy();
    }

    public class LocalBinder extends Binder {
        ChatService getService() {
            // Return this instance of LocalService so clients can call public methods
            return ChatService.this;
        }
    }
}
